//index.js 
//获取应用实例 
const app = getApp()
const util = require('../../utils/util.js')
const lbbService = require('../service/service.js');
import fileUtil from '../../utils/fileUtil.js';
Page({
    data: {
        slideUp: 0,
        userInfo: {},
        pageNum: 1,
        pageSize: 20,
        selectorArray: [0, 0, 0],
        // scrollHeight:'450'
        scrollHeight: '450',
        isRoutingStaticMenus: 0,
        localFileCount: 0,
    },
    onLoad: function () {
        var that = this;
        new Promise(function (resove, reject) {
            app.isAuth(that.getCitys);
            resove();
        }).then(() => {
            util.print('globalData', app.globalData);
            this.getBaseConfig();
        }).catch(() => {
            wx.showToast({
                title: '重新刷新页面',
            })
        });

    },
    onReady: function () {
        let that = this;
        wx.getSystemInfo({
            complete: (res) => {
                app.getWindowHeight(res);
                that.setData({
                    // scrollHeight:app.getScrollHeight(163)
                    //   scrollHeight: app.getScrollHeight(243)
                })
            },
        })
        // lbbService.getUserAuthority({}, res => {
        //   console.log(res.data, '刘奇非要我调')
        //   that.setData({
        //     isshowButton : res.data
        //   })
        // })
    },
    onShow: function () {
        let count = fileUtil.getFiles().length
        console.log('未上传本地文件数量：', count)
        this.setData({
            localFileCount: count
        })
    },
    /**
     * 获取配置信息
     */
    getBaseConfig: function () {
        let that = this;
        lbbService.getBaseConfig({}, res => {
            util.print('config', res);
            app.globalData.config = res;
            that.setData({
                isRoutingStaticMenus: res.isRoutingStaticMenus
            })
        })
    },
    getCitys: function () {
        let that = this;
        lbbService.getCitys({}, function (res) {
            that.setData({
                propArray: res
            })
            that.isAuthLocation(that.getHospitalList)
        })

    },
    isAuthLocation(callback) {
        // 查看是否授权
        let that = this
        wx.getSetting({
            success(res) {
                console.log('wx.getSetting', res)
                var flg = true;
                if (res.authSetting['scope.userLocation']) {
                    console.log("---已授权getLocation")
                    wx.getLocation({
                        type: 'gcj02',
                        success: function (res) {
                            console.log('获取经纬度成功', res)
                            app.globalData.header.lat = parseFloat(res.latitude)
                            app.globalData.header.lng = parseFloat(res.longitude)
                            if (callback) {
                                callback()
                            }
                        },
                        fail: function (res) {
                            wx.showToast({
                                title: '授权失败',
                            })
                            console.log('获取经纬度fail', res)
                            if (callback) {
                                callback()
                            }
                        }
                    })
                } else {
                    console.log("---未授权位置")
                    wx.getLocation({
                        type: 'gcj02',
                        success: function (res) {
                            console.log('用户已授权', res)
                            app.globalData.header.lat = parseFloat(res.latitude)
                            app.globalData.header.lng = parseFloat(res.longitude)
                            if (callback) {
                                callback()
                            }
                        },
                        fail: function (res) {
                            console.log('用户拒绝授权', res)
                            wx.navigateTo({
                                url: '/pages/toAuth/toAuth',
                            })
                        }
                    })
                }
            },
            fail(res) {
                wx.showToast({
                    title: '请打开定位权限',
                })
                console.log('wx.getSetting--fail', res)
            }
        })
    },
    getHospitalList: function () {
        let that = this
        let selectorArray = that.data.selectorArray
        lbbService.getHospitalList({
            array: selectorArray
        }, function (res) {
            that.data.pageNum = 1;
            let accountPhone = wx.getStorageSync('accountPhone')
            if (accountPhone == '12345678901') {
                that.setData({
                    hospitalList: [{
                        chairAmount: 7,
                        hospitalName: "苏州吴中人民医院",
                        id: 14,
                        pileAmount: 10,
                        stretcherAmount: 0,
                        versionIsNew: "new",
                        versions: "H2.1-S2.8.190926"
                    }],
                    hospitalListSolid: '',
                })
                return
            }
            if (res.length > 20) {
                that.setData({
                    hospitalListSolid: res,
                    hospitalList: res.slice(0, 20)
                })
            } else {
                that.setData({
                    hospitalList: res,
                    hospitalListSolid: '',
                })
            }
        })
    },
    getMoreHos() {
        let that = this;
        let pageSize = that.data.pageSize;
        let hospitalListSolid = that.data.hospitalListSolid;
        let hospitalList = that.data.hospitalList;
        if (hospitalListSolid) {
            that.setData({
                hospitalList: hospitalList.concat(hospitalListSolid.slice(that.data.pageNum * pageSize, (that.data.pageNum + 1) * pageSize))
            })
            that.data.pageNum++;
        }
    },
    //监听列表滑动
    scrolled(e) {
        //   if(e.detail.deltaY<0){
        //       this.setData({
        //         slideUp:0
        //       })
        //   }else{
        //     this.setData({
        //         slideUp:1
        //       })
        //   }
    },
    //展开收起
    onExpand() {
        this.setData({
            slideUp: this.data.slideUp==1?0:1
        })
    },
    getUserInfo: function (e) {
        console.log(e)
        app.globalData.userInfo = e.detail.userInfo
        this.setData({
            userInfo: e.detail.userInfo,
            hasUserInfo: true
        })
    },
    searchEventListener: function (e) {
        let that = this
        console.log('searchEventListener>>', e)
        var inputName = '';
        if (e) {
            inputName = e.detail;
            that.setData({
                inputName: inputName
            })
        } else {
            inputName = that.data.inputName;
        }
        console.log('inputName', inputName)
        if (inputName) {
            lbbService.getHospitalByKey({
                key: inputName
            }, function (res) {
                that.data.pageNum = 1;

                // --- 测试代码，上线需删除，桑晟量 start ---
                res.forEach(item => {
                    item.unFinishTask = 8
                })
                // --- 测试代码，上线需删除，桑晟量 end ---

                if (res.length > 20) {
                    that.setData({
                        hospitalListSolid: res,
                        hospitalList: res.slice(0, 20)
                    })
                } else {
                    that.setData({
                        hospitalList: res,
                        hospitalListSolid: '',
                    })
                }
            })
        }
    },
    //事件处理函数
    myEventListener: function (e) {
        let that = this
        console.log("myEventListener>>", e)
        that.setData({
            selectorArray: e.detail,
            cityId: e.detail[1]
        })
        that.getHospitalList()
    },
    // 跳转到点击查看的详情
    navToPage(e) {
        console.log(e, '1234')
        wx.navigateTo({
            url: '../problemSee/problemSee?id=' + e.currentTarget.dataset.id,
        })
    },
    navToProblemList(e) {
        wx.navigateTo({
            url: '../problemList/problemList?hospitalId=' + e.currentTarget.dataset.id,
        })
    },
    // 跳转到任务列表
    navToTaskList(e) {
        wx.navigateTo({
            url: '/pkgTask/pages/task-list/index?hospitalId=' + e.currentTarget.dataset.id,
        })
    },
    // 跳转到巡检总汇
    inspectionCompany(e) {
        wx.navigateTo({
            url: '../inspectionCompany/inspectionCompany',
        })
    },
    // 跳转到问题总汇
    problemCompany(e) {
        wx.navigateTo({
            url: '../problemCompany/problemCompany',
        })
    },
    updateCompany(e) {
        wx.navigateTo({
            url: '../updateCompany/updateCompany',
        })
    },
    refresh() {
        wx.showLoading({
            title: '请等待',
        })
        lbbService.updateHospitalProblems({}, function (res) {
            wx.hideLoading()
        })
    },
    batteryStatistics: function () {
        wx.navigateTo({
            url: '../batteryWarningList/batterylist',
        })
    },
    simStatistics: function () {
        wx.navigateTo({
            url: '../simWarningList/simWarningList',
        })
    },
    goUploadLocalFiles() {
        wx.navigateTo({
            url: '/pkgTask/pages/upload-local-files/index',
        })
    },
    onClose(event) {
        var that = this;
        const {
            position,
            instance
        } = event.detail;
        switch (position) {
            case 'left':
            case 'cell':
                break;
            case 'right':
                lbbService.handleMechanismTop({
                    hospitalId: event.currentTarget.dataset.id,
                    handleType: event.currentTarget.dataset.istop == 1 ? 0 : 1
                }, function (res) {
                    if (event.currentTarget.dataset.istop == 1) {
                        that.data.hospitalList[event.currentTarget.dataset.index].isTop = 0
                        that.setData({
                            hospitalList: that.data.hospitalList
                        })
                    } else {
                        let newItem = event.currentTarget.dataset.info
                        newItem.isTop = 1
                        that.data.hospitalList.splice(event.currentTarget.dataset.index, 1)
                        that.data.hospitalList = [newItem, ...that.data.hospitalList]
                        that.setData({
                            hospitalList: that.data.hospitalList
                        })
                    }

                    instance.close();
                })


                break;
        }
    }
})